package top.simonby.iron.base.vo;


import io.swagger.v3.oas.annotations.media.Schema;
import lombok.*;
import lombok.experimental.Accessors;
import top.simonby.iron.base.constant.CommonConstants;

import java.io.Serializable;

/**
 * 响应信息主体
 *
 * @author 91223
 */
@ToString
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
@Schema(name = "响应信息主体")
public class R<T> implements Serializable {
    private static final long serialVersionUID = 1L;

    @Getter
    @Setter
    @Schema(name = "返回标记：成功标记=true，失败标记=false")
    private boolean success;

    @Getter
    @Setter
    @Schema(name = "返回标记：成功标记=0，失败标记=1")
    private int code;

    @Getter
    @Setter
    @Schema(name = "返回标记：业务code")
    private int httpCode;

    @Getter
    @Setter
    @Schema(name = "返回信息")
    private String msg;


    @Getter
    @Setter
    @Schema(name = "返回信息")
    private T data;

    /**
     * 响应成功
     */
    public static <T> R<T> ok() {
        return restResult(null, CommonConstants.SUCCESS, 200, null);
    }

    /**
     * 响应成功
     *
     * @param data 数据
     */
    public static <T> R<T> ok(T data) {
        return restResult(data, CommonConstants.SUCCESS, 200, null);
    }

    /**
     * 响应成功
     *
     * @param data 数据
     * @param msg  消息
     */
    public static <T> R<T> ok(T data, String msg) {
        return restResult(data, CommonConstants.SUCCESS, 200, msg);
    }

    /**
     * 响应失败
     */
    public static <T> R<T> failed() {
        return restResult(null, CommonConstants.FAIL, 400, null);
    }

    /**
     * 响应失败
     */
    public static <T> R<T> failed(int httpCode) {
        return restResult(null, CommonConstants.FAIL, httpCode, null);
    }

    /**
     * 响应失败
     *
     * @param msg 消息
     */
    public static <T> R<T> failed(int httpCode, String msg) {
        return restResult(null, CommonConstants.FAIL, httpCode, msg);
    }

    /**
     * 响应失败
     *
     * @param data 数据
     */
    public static <T> R<T> failed(int httpCode, T data) {
        return restResult(data, CommonConstants.FAIL, httpCode, null);
    }

    /**
     * 响应失败
     *
     * @param data 数据
     * @param msg  消息
     */
    public static <T> R<T> failed(int httpCode, T data, String msg) {
        return restResult(data, CommonConstants.FAIL, httpCode, msg);
    }

    /**
     * 响应失败
     *
     * @param code 成功0/失败1
     * @param data 数据
     * @param msg  消息
     */
    private static <T> R<T> restResult(T data, int code, int httpCode, String msg) {
        R<T> apiResult = new R<>();
        apiResult.setSuccess(code == 0);
        apiResult.setCode(code);
        apiResult.setHttpCode(httpCode);
        apiResult.setData(data);
        apiResult.setMsg(msg);
        return apiResult;
    }
}
